import MusenumUserModel from "../model/musenumUser";
import MusenumUserTimesModel from "../model/musenumUserTimes";
import { gainAllSystemConfigLogin } from "../thirdServices/museumApi";

/**每日下午5点执行 */

class MuseumTimesTask {
  async execute(page = 1) {
    const userModel = await MusenumUserModel.findOneAvailable();
    if (userModel) {
      const token = userModel.getDataValue('token');
      const res = await gainAllSystemConfigLogin(token);
      if (res.data.code === 200) {
        const list = res.data.data.calendarTicketPoolsByDate;
        const dateList = list.filter(item => [3, 4].includes(item.status)).map(item => item.currentDate);
        
        const userListRes = await MusenumUserModel.getlist(1);
        for (let i = 0; i< userListRes.rows.length; i++) {
          const user = userListRes.rows[i];
          const userid = user.getDataValue('uuid');
          const phonenumber = user.getDataValue('phonenumber');
          const token = user.getDataValue('token');
          this.createUserTimes(userid, phonenumber, token, dateList);
        }

        if (page * 20 < userListRes.count) {
          this.execute(page + 1);
        }
      } 
    }
  }

  async executeByUser(userInfo) {
    const res = await gainAllSystemConfigLogin(userInfo.token);
    if (res.data.code === 200) {
      const list = res.data.data.calendarTicketPoolsByDate;
      const dateList = list.filter(item => [3, 4].includes(item.status)).map(item => item.currentDate);
      this.createUserTimes(userInfo.userId, userInfo.phoneNumber,  userInfo.token, dateList);
    } else {
      console.log(res.data)
    }
  }

  async createUserTimes(userid, phonenumber, token, dateList) {
    for(let i = 0; i < dateList.length;i++) {
      const item = await MusenumUserTimesModel.findOneByDate(userid, dateList[i]);
      if (!item) {
        let data: any = { userid, date: dateList[i], phonenumber, token, platform: 1 };
        await MusenumUserTimesModel.insert(data);
      }
    }
  }
}

export default MuseumTimesTask;